package com.ifacebox.face.track.utils;

import com.arcsoft.face.Rect;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author znn19
 */
public class ImageUtils {
    private static final Dimension CUT_FACE_SIZE = new Dimension(50, 50);
    private static final String IMAGE_FORMAT = "jpg";

    public static BufferedImage readImage(byte[] bytes) {
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            return ImageIO.read(is);
        } catch (IOException e) {
            throw new RuntimeException(String.format("读取图片异常！(%s)", e.getMessage()));
        }
    }

    public static BufferedImage readImage(File file) {
        try {
            return ImageIO.read(file);
        } catch (IOException e) {
            throw new RuntimeException(String.format("读取图片异常！(%s)", e.getMessage()));
        }
    }

    public static byte[] readImage(BufferedImage image) {
        if (image == null) {
            return null;
        }
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ImageIO.write(image, IMAGE_FORMAT, os);
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(String.format("读取图片异常！(%s)", e.getMessage()));
        }
    }

    public static BufferedImage cutImage(BufferedImage image, Rect rect) {
        Rectangle newValue = new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
        newValue.grow(CUT_FACE_SIZE.width, CUT_FACE_SIZE.height);
        Rectangle oldValue = new Rectangle(0, 0, image.getWidth(), image.getHeight());
        Rectangle value = oldValue.intersection(newValue);
        return image.getSubimage(value.x, value.y, value.width, value.height);
    }

    public static Image scaledImage(BufferedImage image, Dimension size, boolean fill) {
        if (fill) {
            return image.getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH);
        }
        if (image.getWidth() < image.getHeight()) {
            return image.getScaledInstance(-1, size.height, Image.SCALE_SMOOTH);
        } else {
            return image.getScaledInstance(size.width, -1, Image.SCALE_SMOOTH);
        }
    }

    @Deprecated
    public static BufferedImage drawImage(Image img) {
        BufferedImage image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.drawImage(img, 0, 0, null);
        g2.dispose();
        return image;
    }
}
